// pages/cocktail/cocktail.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    selectedMood: '',
    selectedWeather: '',
    selectedScene: '',
    selectedNote: '',
    customMood: '',
    customWeather: '',
    customScene: '',
    customNote: '',
    historyPerfumes: [],
    hasMorePerfumeHistory: false,
    bannerImage: '/images/xiangshui.jpg',
    moodOptions: ['放松', '愉快', '忧郁', '兴奋', '平静', '浪漫'],
    weatherOptions: ['晴天', '雨天', '阴天', '雪天', '雾天', '风大'],
    sceneOptions: ['约会', '聚会', '独处', '工作', '旅行', '运动'],
    noteOptions: ['花香', '果香', '木质', '东方', '清新', '美食'],
    isLoading: false,
    serverUrl: '',
    isTestMode: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 从全局配置获取服务器地址
    const app = getApp();
    this.setData({
      serverUrl: app.globalData.serverUrl
    });
    
    this.loadPerfumeHistory();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 1
      });
    }
  },

  /**
   * 选择心情
   */
  selectMood: function(e) {
    this.setData({
      selectedMood: e.currentTarget.dataset.mood
    });
  },

  /**
   * 选择天气
   */
  selectWeather: function(e) {
    this.setData({
      selectedWeather: e.currentTarget.dataset.weather
    });
  },

  /**
   * 选择场景
   */
  selectScene: function(e) {
    this.setData({
      selectedScene: e.currentTarget.dataset.scene
    });
  },

  /**
   * 选择香调
   */
  selectNote: function(e) {
    this.setData({
      selectedNote: e.currentTarget.dataset.note
    });
  },

  /**
   * 自定义输入变化
   */
  onCustomInputChange: function(e) {
    const { type } = e.currentTarget.dataset;
    this.setData({
      [type]: e.detail.value
    });
  },

  /**
   * 生成香水推荐
   */
  generatePerfume: function() {
    if (!this.data.selectedMood && !this.data.selectedWeather && !this.data.selectedScene && !this.data.selectedNote && !this.data.customMood && !this.data.customWeather && !this.data.customScene && !this.data.customNote) {
      wx.showToast({
        title: '请至少选择一项',
        icon: 'none'
      });
      return;
    }
    this.setData({ isLoading: true });
    let mood = this.data.selectedMood || this.data.customMood || '放松';
    let weather = this.data.selectedWeather || this.data.customWeather || '晴天';
    let scene = this.data.selectedScene || this.data.customScene || '约会';
    let note = this.data.selectedNote || this.data.customNote || '花香';
    wx.request({
      url: `${this.data.serverUrl}/api/perfume`,
      method: 'POST',
      data: { mood, weather, scene, note },
      success: (res) => {
        this.setData({ isLoading: false });
        if (res.data.success) {
          // 只保存香水推荐结构
          this.savePerfumeHistory({
            name: res.data.name || '香水推荐',
            formula: res.data.formula || `${mood} / ${weather} / ${scene} / ${note}`,
            img: res.data.img || '/images/perfume_default.png',
            desc: res.data.desc || '',
            detail: res.data
          });
          wx.navigateTo({
            url: '/pages/result/result?source=perfume&data=' + encodeURIComponent(JSON.stringify(res.data))
          });
        } else {
          wx.showToast({ title: '推荐失败', icon: 'none' });
        }
      },
      fail: (err) => {
        this.setData({ isLoading: false });
        wx.showToast({ title: '网络错误，请重试', icon: 'none' });
      }
    });
  },

  /**
   * 保存香水推荐到本地历史，只保留香水结构
   */
  savePerfumeHistory: function(item) {
    try {
      let history = wx.getStorageSync('perfume_history') || [];
      // 过滤掉非香水结构（如有cocktailName等字段的）
      history = history.filter(h => !h.cocktailName && !h.baseSpirits);
      history.push({
        name: item.name,
        formula: item.formula,
        img: item.img,
        desc: item.desc,
        detail: item.detail
      });
      wx.setStorageSync('perfume_history', history);
      this.loadPerfumeHistory();
    } catch (e) {
      console.error('保存香水历史失败:', e);
    }
  },

  /**
   * 加载香水历史，只展示香水结构
   */
  loadPerfumeHistory: function() {
    try {
      let historyList = wx.getStorageSync('perfume_history') || [];
      // 过滤掉非香水结构（如有cocktailName等字段的）
      historyList = historyList.filter(h => !h.cocktailName && !h.baseSpirits);
      if (historyList.length > 0) {
        const recentHistory = historyList.slice(-3).reverse().map((item, index) => ({
          ...item,
          originalIndex: historyList.length - 1 - index
        }));
        this.setData({
          historyPerfumes: recentHistory,
          hasMorePerfumeHistory: historyList.length > 3
        });
      } else {
        this.setData({
          historyPerfumes: [],
          hasMorePerfumeHistory: false
        });
      }
    } catch (e) {
      console.error('获取香水历史记录失败:', e);
    }
  },

  /**
   * 查看单条历史香水推荐
   */
  viewHistoryPerfume: function(e) {
    const index = e.currentTarget.dataset.index;
    const originalIndex = this.data.historyPerfumes[index].originalIndex;
    wx.navigateTo({
      url: '/pages/result/result?id=' + originalIndex + '&source=perfume_history'
    });
  },

  /**
   * 查看全部历史香水推荐
   */
  viewAllPerfumeHistory: function() {
    wx.navigateTo({
      url: '/pages/history/history?source=perfume_history'
    });
  },
  
  /**
   * 测试API数据
   */
  testApiData: function() {
    const testApiData = {
      "code": 0,
      "cost": "0",
      "data": "{\"cocktailName\":\"云端苦旅\",\"cost\":\"成本约(28元)\",\"data\":\"https://s.coze.cn/t/SwZBfMvc1ik/\",\"formula\":{\"baseSpirits\":\"威士忌45毫升 + 圣日耳曼接骨木花利口酒(15ml)\",\"flavorElements\":\"苦艾酒10毫升+咖啡糖浆15毫升。\"}",
      "debug_url": " https://www.coze.cn/work_flow?execute_id=7519477143471783948&space_id=7519408155462828070&workflow_id=7519427325491560482&execute_mode=2",
      "msg": "Success",
      "token": 1730
    };
    
    // 显示加载中
    this.setData({
      isLoading: true
    });
    
    // 模拟加载过程
    setTimeout(() => {
      this.setData({
        isLoading: false
      });
      
      try {
        // 跳转到结果页面，传递测试数据
        wx.navigateTo({
          url: `/pages/result/result?apiData=${encodeURIComponent(JSON.stringify(testApiData))}`
        });
      } catch (error) {
        console.error('处理测试数据失败:', error);
        wx.showToast({
          title: '测试数据处理失败',
          icon: 'none'
        });
      }
    }, 1000); // 延迟1秒，模拟网络请求
  },

  /**
   * 清空香水历史（调试用）
   */
  clearPerfumeHistory: function() {
    wx.removeStorageSync('perfume_history');
    this.setData({
      historyPerfumes: [],
      hasMorePerfumeHistory: false
    });
    wx.showToast({ title: '香水历史已清空', icon: 'none' });
  }
}) 